package com.sumer.psychology.common.query;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;

import java.util.regex.Pattern;

/**
 * 基本查询服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/11/3
 * Time: 15:46
 */
public abstract class AbstractSimpleQueryApplicationService extends AbstractMongoRepository {
    /**
     * 关键字查询
     *
     * @param keyword         key word
     * @param countPerPage    count per page
     * @param offset          off set
     * @param keywordProperty keyword property
     * @return json
     */
    public String findByKeyword(String keyword, int countPerPage, int offset, String keywordProperty) {
        DBObject queryCondition = new BasicDBObject(
                keywordProperty,
                Pattern.compile(".*" + keyword + ".*", Pattern.CASE_INSENSITIVE));

        return findByCondition(countPerPage, offset, queryCondition);
    }

    /**
     * 展现热门(评论最多的)
     *
     * @param limit 限制个数
     * @return json
     */
    public String displayTopics(int limit) {
        DBCursor results = db().getCollection(dbName())
                .find()
                .sort(new BasicDBObject().append("replies", -1).append("createTime", -1))
                .limit(limit);

        return JSON.serialize(results.toArray());
    }

    /**
     * 查询作者下的
     *
     * @param authorId        author id
     * @param countPerPage    count per page
     * @param offset          off set
     * @param keyword         key word
     * @param keywordProperty keyword property
     * @return json
     */
    public String findByAuthor(String authorId, int countPerPage, int offset, String keyword, String keywordProperty) {
        DBObject queryCondition = new BasicDBObject()
                .append("author.identity", authorId)
                .append(keywordProperty, Pattern.compile(".*" + keyword + ".*", Pattern.CASE_INSENSITIVE));

        return findByCondition(countPerPage, offset, queryCondition);
    }

    /*
     * 根据条件查询
     */
    protected String findByCondition(int countPerPage, int offset, DBObject queryCondition) {
        DBCursor results = db().getCollection(dbName())
                .find(queryCondition)
                .sort(new BasicDBObject("createTime", -1))
                .skip(offset)
                .limit(countPerPage);

        return serializeWithTotalCount(queryCondition, results);
    }

    protected DBCursor findListByCondition(int countPerPage, int offset, DBObject queryCondition) {
        return db().getCollection(dbName())
                .find(queryCondition)
                .sort(new BasicDBObject("createTime", -1))
                .skip(offset)
                .limit(countPerPage);
    }

}
